#--------------------------------------------------#
#flight.r是业务逻辑层中的R脚本，包含一个函数用来完成单一功能
#
#航班航行距离与延误时间的关系
#--------------------------------------------------#


library(dplyr)
library(nycflights13)# for data
summary(flights)#On-time data for all flights that departed NYC (i.e. JFK, LGA or EWR) in 2013.
#输入：不需要输入参数
#输出：返回每个目的地的平均航行距离，平均延误时间

disDelay <- function(){
  #选择子集
  myFlights <- select(flights,
                      year,month,day,
                      dep_delay,arr_delay,
                      distance,dest)
  #列名重命名，等号左边是新列名，右边是就列名
  myFlights <- rename(myFlights, destination = dest)
  
  #删除缺失数据，这里的空值NA代表航班取消
  myFlights <- filter(myFlights, #删除，返回的数据框不包含以下值
                      !is.na(dep_delay), 
                      !is.na(arr_delay))
  
  #数据排序
  myFlights <- arrange(myFlights, desc(dep_delay)) # select * FROM myflights order by dep_delay DESC
  ?summarise
  #数据计算：航班航行距离与延误时间的关系    
  delay <- myFlights %>% 
    group_by(destination) %>% #没完，接下来对分组的数据进行计算，
    summarise(
      count = n(),
      dist = mean(distance, na.rm = TRUE),
      delay = mean(arr_delay, na.rm = TRUE)
    ) %>% 
    filter(count > 20)
  #SELECT destination, count(1) AS count,AVG(distance) AS dist,AVG(arr_delay) AS delay FROM myFlights GROUP BY destination WHERE count>20.
  
  return(delay)
  #整个函数对flight数据进行操作，根据目的地进行分组
}
